const { success, failure } = require("../../utils/responses");
const generatorsServices = require("../../services/system/generatorsService");
const generatorTool = require("../../utils/codeGenerator/generatorTool.js");
/**
 * 查询代码生成列表
 * @param req
 * @param res
 */
exports.list = async (req, res) => {
  try {
    // 分页查询
    const { count, rows, currentPage, pageSize } =
      await generatorsServices.list(req);
    // 返回
    success(res, "代码生成查询成功", {
      lists: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 查询代码生成列表
 * @param req
 * @param res
 */
exports.all = async (req, res) => {
  try {
    const rows = await generatorsServices.all(req);
    // 返回
    success(res, "代码生成查询成功", rows);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 查询代码生成详情
 * @param req
 * @param res
 */
exports.detail = async (req, res) => {
  try {
    const generator = await generatorsServices.getById(req);
    success(res, "查询代码生成成功", generator);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 创建代码生成
 * @param req
 * @param res
 */
exports.add = async (req, res) => {
  try {
    const body = filterBody(req);
    const generator = await generatorsServices.create(body);
    //创建工具类实例
    const tool = new generatorTool();
    //生成代码
    await tool.generateCode({
      tableName: generator.tableName,
      modelName: generator.modelName,
      fields: generator.fields,
      title: generator.title,
      routerPath: generator.routerPath,
    });
    success(res, "创建代码生成成功", generator, 201);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 删除代码生成
 * @param req
 * @param res
 */
exports.del = async (req, res) => {
  try {
    await generatorsServices.del(req.body.id);
    success(res, "删除代码生成成功");
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新代码生成
 * @param req
 * @param res
 */
exports.update = async (req, res) => {
  try {
    const body = filterBody(req);
    const generator = await generatorsServices.update(req.body.id, body);
    //创建工具类实例
    const tool = new generatorTool();
    //生成代码
    await tool.generateCode({
      tableName: generator.tableName,
      modelName: generator.modelName,
      fields: generator.fields,
      title: generator.title,
      routerPath: generator.routerPath,
    });
    success(res, "更新代码生成成功", generator);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 公共方法过滤白名单
 * @param req
 */
function filterBody(req) {
  return {
    tableName: req.body.tableName, // 数据库表名
    modelName: req.body.modelName, // 模型名
    fields: req.body.fields, // 字段名
    title: req.body.title, // 业务名
    routerPath: req.body.routerPath, // 模块名
  };
}
